from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.utils import timezone
from LogisticsCard.models import Cards, Customer, CardOrder, CardOrderCard, UserPriceConfig, CardUserRelation, UserProfile

@login_required
def renew_select_customer_view(request):
    user = request.user
    is_admin = user.is_superuser or (hasattr(user, 'profile') and getattr(user.profile, 'type', None) == 'admin')
    if not is_admin:
        return redirect('renew_select_cards')
    customers = Customer.objects.filter(delete_at__isnull=True)
    return render(request, 'orders/renew_select_customer.html', {
        'customers': customers,
    })

@login_required
def renew_select_cards_view(request):
    query = request.GET.get('q', '')
    page_size = int(request.GET.get('page_size', 20))
    page_number = request.GET.get('page', 1)
    user = request.user
    is_admin = user.is_superuser or (hasattr(user, 'profile') and getattr(user.profile, 'type', None) == 'admin')
    customer_id = request.GET.get('customer_id')
    cards = Cards.objects.filter(delete_at__isnull=True)
    if is_admin:
        # 管理员需先选客户
        if not customer_id:
            return redirect('renew_select_customer')
        print(customer_id)
        cards = cards.filter(carduserrelation__customer_id=customer_id)
    else:
        # 普通用户只显示自己关联客户的卡
        profile = getattr(user, 'profile', None)
        if profile:
            rel_customers = Customer.objects.filter(user=user, delete_at__isnull=True)
            if rel_customers.exists():
                cards = cards.filter(carduserrelation__customer__in=rel_customers)
    if query:
        cards = cards.filter(iccid__icontains=query)
    cards = cards.order_by('-packageTime')
    paginator = Paginator(cards, page_size)
    page_obj = paginator.get_page(page_number)
    return render(request, 'orders/renew_select_cards.html', {
        'page_obj': page_obj,
        'query': query,
        'page_size': page_size,
        'sizes': [10, 20, 50, 100],
        'is_admin': is_admin,
        'customer_id': customer_id,
    })

@login_required
def renew_confirm_view(request):
    if request.method == 'POST':
        card_ids = request.POST.getlist('card_ids')
        packages = request.POST.getlist('packages')
        customer_id = request.POST.get('customer_id')
        cards = Cards.objects.filter(id__in=card_ids, delete_at__isnull=True)
        customer = Customer.objects.get(id=customer_id)
        total_price = 0
        price_list = []
        for index,card in enumerate(cards):
            print(card)
            print(customer)
            print(packages[index])
            price_obj = UserPriceConfig.objects.filter(customer=customer, package=packages[index]).first()
            price = price_obj.price if price_obj else 0
            price_list.append({'card': card, 'price': price})
            total_price += price
        can_modify = request.user.is_superuser or (hasattr(request.user, 'profile') and getattr(request.user.profile, 'type', None) == 'admin')
        return render(request, 'orders/renew_confirm.html', {
            'cards': cards,
            'price_list': price_list,
            'total_price': total_price,
            'can_modify': can_modify,
            'packages': packages,
            'customer': customer,
        })
    return redirect('renew_select_cards')

@login_required
def renew_submit_view(request):
    if request.method == 'POST':
        card_ids = request.POST.getlist('card_ids')
        package = request.POST.get('package')
        customer_id = request.POST.get('customer_id')
        amount = request.POST.get('amount')
        cards = Cards.objects.filter(id__in=card_ids, delete_at__isnull=True)
        customer = Customer.objects.get(id=customer_id)
        from datetime import datetime
        import random
        now = datetime.now()
        time_str = now.strftime('%Y%m%d%H%M%S%f')[:20]
        rand_str = f"{random.randint(0, 9999):04d}"
        order_no = f"X{time_str}{rand_str}"
        order = CardOrder.objects.create(
            order_type='renew',
            order_no=order_no,
            customer=customer,
            package=package,
            card_count=len(cards),
            amount=amount,
            status='pending',
            receiver=customer.username,
            delivery_phone=customer.phone,
            delivery_address=customer.address,
        )
        for card in cards:
            CardOrderCard.objects.create(order=order, card=card)
        return redirect(f'/order/pay/{order.id}/')
    return redirect('renew_select_cards')
